package com.chen.palmar.project.home;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chen.palmar.R;
import com.chen.palmar.base.BaseActivity;
import com.chen.palmar.common.constant.AppConstant;
import com.chen.palmar.common.datasource.CommentRequest;
import com.chen.palmar.common.datasource.DataCenter;
import com.chen.palmar.common.override.BannerImageLoader;
import com.chen.palmar.common.override.HttpSubscriber;
import com.chen.palmar.common.widget.view.AutoToolbar;
import com.chen.palmar.common.widget.view.CircleImageView;
import com.chen.palmar.entity.CollectEntity;
import com.chen.palmar.entity.DetailEntity;
import com.chen.palmar.entity.GoodEntity;
import com.chen.palmar.project.agency.AgencyDetailActivity;
import com.chen.palmar.project.producer.ProducerDetailActivity;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.primb.androidlibs.net.entity.HttpResultEntity;
import com.primb.androidlibs.net.entity.MessageEvent;
import com.primb.androidlibs.net.exception.ApiException;
import com.primb.androidlibs.ui.recyclerview.BaseQuickAdapter;
import com.primb.androidlibs.ui.recyclerview.BaseViewHolder;
import com.primb.androidlibs.utils.DoubleClickExitDetector;
import com.squareup.picasso.Picasso;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import rx.Subscription;

import static com.chen.palmar.project.home.ApplyInfoActivity.EVENT_INFO_CODE;
import static com.mob.MobSDK.getContext;

/**
 * @author Chen
 * @date 2018/1/3
 * 功能描述：
 */

public class InfoDetailActivity extends BaseActivity {
    @Bind(R.id.title_bar)
    TextView titleBar;
    @Bind(R.id.iv_top)
    ImageView ivTop;
    @Bind(R.id.tool_bar)
    AutoToolbar toolBar;
    @Bind(R.id.iv_item_home_head)
    CircleImageView ivItemHomeHead;
    @Bind(R.id.tv_item_home_name)
    TextView tvItemHomeName;
    @Bind(R.id.tv_item_date)
    TextView tvItemDate;
    @Bind(R.id.tv_item_home_state)
    TextView tvItemHomeState;
    @Bind(R.id.tv_item_home_type)
    TextView tvItemHomeType;
    @Bind(R.id.tv_item_home_content)
    TextView tvItemHomeContent;
    @Bind(R.id.rv_item_home_img)
    RecyclerView rvItemHomeImg;
    @Bind(R.id.tv_item_home_location)
    TextView tvItemHomeLocation;
    @Bind(R.id.tv_item_home_good)
    TextView tvItemHomeGood;
    @Bind(R.id.iv_item_home_good)
    ImageView ivItemHomeGood;
    @Bind(R.id.tv_item_home_watch)
    TextView tvItemHomeWatch;
    @Bind(R.id.rv_detail_comment)
    RecyclerView rvDetailComment;
    @Bind(R.id.tv_detail_comment)
    TextView tvDetailComment;
    @Bind(R.id.tv_detail_good)
    TextView tvDetailGood;
    @Bind(R.id.tv_detail_contact)
    TextView tvDetailContact;
    @Bind(R.id.banner_detail)
    Banner bannerDetail;
    private BaseQuickAdapter<String, BaseViewHolder> adapterImg;
    private BaseQuickAdapter<DetailEntity.DataBean.CommentsBean, BaseViewHolder> adapterComment;
    private List<Object> images = new ArrayList<>();
    private DetailEntity detailEntity;
    private DoubleClickExitDetector doubleClickExitDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    public void init() {
        titleBar.setText("详情");
        toolBar.setNavigationOnClickListener(v -> InfoDetailActivity.this.finish());
        ivTop.setVisibility(View.VISIBLE);
        ivTop.setImageResource(R.mipmap.info_top_icon);
        ivTop.setTag(false);
        tvItemHomeState.setVisibility(View.GONE);
        tvItemHomeType.setVisibility(View.GONE);
        tvItemHomeGood.setVisibility(View.GONE);
        ivItemHomeGood.setVisibility(View.GONE);

        //设置指示器位置（当banner模式中有指示器时）
        bannerDetail.setIndicatorGravity(BannerConfig.CENTER);
        bannerDetail.setImageLoader(new BannerImageLoader());

        rvItemHomeImg.setNestedScrollingEnabled(false);
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 3);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvItemHomeImg.setLayoutManager(layoutManager);
        adapterImg = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_home_img) {
            @Override
            protected void convert(BaseViewHolder helper, String item) {
                ImageView view = (ImageView) helper.getView(R.id.iv_item_img);
                Picasso.with(getContext()).load(item).resize(AppConstant.SCREEN_WIDTH / 3, AppConstant.SCREEN_WIDTH / 4).placeholder(R.mipmap.occupy_icon).error(R.mipmap.occupy_icon).into(view);
            }
        };
        rvItemHomeImg.setItemAnimator(new DefaultItemAnimator());
        rvItemHomeImg.setAdapter(adapterImg);

        rvDetailComment.setNestedScrollingEnabled(false);
        LinearLayoutManager layoutManagerComment = new LinearLayoutManager(getContext());
        layoutManagerComment.setOrientation(LinearLayoutManager.VERTICAL);
        rvDetailComment.setLayoutManager(layoutManagerComment);
        adapterComment = new BaseQuickAdapter<DetailEntity.DataBean.CommentsBean, BaseViewHolder>(R.layout.item_detail_comment) {
            @Override
            protected void convert(BaseViewHolder helper, DetailEntity.DataBean.CommentsBean item) {
                CircleImageView head = (CircleImageView) helper.getView(R.id.iv_item_comment_head);
                Picasso.with(getContext()).load(item.getAvatar()).resize(AppConstant.SCREEN_WIDTH / 3, AppConstant.SCREEN_WIDTH / 3).placeholder(R.mipmap.home_item_head_icon).error(R.mipmap.home_item_head_icon).into(head);
                helper.setText(R.id.tv_item_comment_name, item.getName());
                helper.setText(R.id.tv_item_comment_date, item.getCreate_at());
                helper.setText(R.id.tv_item_comment_content, item.getContent());
            }
        };
        rvDetailComment.setItemAnimator(new DefaultItemAnimator());
        rvDetailComment.setAdapter(adapterComment);

        String info = getIntent().getStringExtra("info");

        try {
            getDataForWeb(info);
        } catch (Exception e) {
            e.printStackTrace();
            showToast("服务器数据出错，请稍后重试");
        }

        doubleClickExitDetector = new DoubleClickExitDetector(this);
        doubleClickExitDetector.setEffectiveIntervalTime(1500);
    }

    private void getDataForWeb(String articleId) throws Exception {
        if (TextUtils.isEmpty(articleId)) {
            showToast("数据错误（详情id为空）");
            return;
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("articleId", articleId);
        Subscription subscribe = DataCenter.detailInfo(map).subscribe(new HttpSubscriber<DetailEntity>(this, showLoading("加载中")) {
            @Override
            public void onNext(DetailEntity detailEntity) {
                try {
                    setDataToView(detailEntity);
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("服务器数据格式异常");
                }
            }
        });
        subscription.add(subscribe);
    }

    private void setDataToView(DetailEntity detailEntity) throws Exception {
        this.detailEntity = detailEntity;
        DetailEntity.DataBean data = detailEntity.getData();
        images.clear();
        images.addAll(data.getImgList());
        bannerDetail.setImages(images);
        bannerDetail.start();

        adapterImg.setNewData(data.getImgList());
        adapterComment.setNewData(data.getComments());

        tvItemDate.setText(data.getCreate_at());
        tvItemHomeContent.setText(data.getContent());
        tvItemHomeName.setText(data.getUser_name());
        tvItemHomeLocation.setText(data.getAddress_detail());
        tvItemHomeWatch.setText(data.getBrowse_nums() + "");
        tvItemHomeType.setText("1".equals(data.getType()) ? "供应" : "采购");
        tvItemHomeState.setText(data.getLabelName());
        tvItemHomeState.setVisibility(View.VISIBLE);

        tvDetailGood.setText(data.getPraise_nums() + "");

        Glide.with(getContext()).load(data.getUser_avatar()).placeholder(R.mipmap.home_item_head_icon).error(R.mipmap.home_item_head_icon).fitCenter().into(ivItemHomeHead);

        ivTop.setTag(data.getFavoriteStatus() == 1);
        ivTop.setImageResource(((boolean) ivTop.getTag()) ? R.mipmap.info_toped_icon : R.mipmap.info_top_icon);

        Drawable normal = ContextCompat.getDrawable(InfoDetailActivity.this, R.mipmap.info_good_icon);
        Drawable select = ContextCompat.getDrawable(InfoDetailActivity.this, R.mipmap.info_gooded_icon);
        tvDetailGood.setCompoundDrawablesWithIntrinsicBounds(null, data.getPraiseStatus() == 1 ? select : normal, null, null);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_detail_info;
    }

    @OnClick({R.id.tv_detail_comment, R.id.tv_detail_good, R.id.tv_detail_contact, R.id.iv_top, R.id.iv_item_home_head, R.id.tv_item_home_name})
    public void onViewClicked(View view) {
        if (detailEntity == null) {
            showToast("服务器返回数据为空,重试中");
            try {
                getDataForWeb(getIntent().getStringExtra("info"));
            } catch (Exception e) {
                e.printStackTrace();
                showToast("服务器数据出错，请稍后重试");
            }
            return;
        }
        if (!doubleClickExitDetector.clickView()) {
            return;
        }
        switch (view.getId()) {
            case R.id.iv_top:
                collectInfo(((boolean) ivTop.getTag()));
                break;
            case R.id.tv_detail_comment:
                commentInfo();
                break;
            case R.id.tv_detail_good:
                goodInfo();
                break;
            case R.id.tv_detail_contact:
                contractInfo();
                break;
            case R.id.iv_item_home_head:
            case R.id.tv_item_home_name:
                Intent intent = new Intent();
                if (detailEntity.getData().getUser_type() == 1) {
                    intent.setClass(InfoDetailActivity.this, ProducerDetailActivity.class);
                } else {
                    intent.setClass(InfoDetailActivity.this, AgencyDetailActivity.class);
                }
                intent.putExtra("info", detailEntity.getData().getCompany_id() + "");
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CommentRequest.cancelRequest();
    }

    /**
     * 收藏
     *
     * @param tag
     */
    private void collectInfo(boolean tag) {
        CommentRequest.collectInfo(detailEntity.getData().getArticleId() + "", "1", tag, new CommentRequest.OnLoadSuccessListener<CollectEntity>() {
            @Override
            public void onSuccess(CollectEntity entity) {
                if (!TextUtils.isEmpty(entity.getMessage())) {
                    showToast(entity.getMessage());
                    ivTop.setTag(!tag);
                    ivTop.setImageResource(((boolean) ivTop.getTag()) ? R.mipmap.info_toped_icon : R.mipmap.info_top_icon);
                    EventBus.getDefault().post(new MessageEvent(EVENT_INFO_CODE));
                }
            }

            @Override
            public void onFailure(ApiException e) {
                if ("已收藏，请勿重复收藏".equals(e.getMessage())) {
                    ivTop.setTag(!tag);
                    ivTop.setImageResource(R.mipmap.info_toped_icon);
                }
            }
        });
    }

    /**
     * 评论
     */
    private void commentInfo() {
        CommentRequest.commentInfo(this, getSupportFragmentManager(), detailEntity.getData().getArticleId() + "", "1", new CommentRequest.OnLoadSuccessListener<HttpResultEntity>() {
            @Override
            public void onSuccess(HttpResultEntity entity) {
                showToast(entity.getMessage());
                Drawable select = ContextCompat.getDrawable(InfoDetailActivity.this, R.mipmap.info_commented_icon);
                tvDetailComment.setCompoundDrawablesWithIntrinsicBounds(null, select, null, null);
                EventBus.getDefault().post(new MessageEvent(EVENT_INFO_CODE));
                try {
                    getDataForWeb(getIntent().getStringExtra("info"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(ApiException e) {

            }
        });
    }

    /**
     * 点赞
     */
    private void goodInfo() {
        CommentRequest.goodInfo(detailEntity.getData().getArticleId() + "", new CommentRequest.OnLoadSuccessListener<GoodEntity>() {
            @Override
            public void onSuccess(GoodEntity entity) {
                showToast(entity.getMessage());
                Drawable select = ContextCompat.getDrawable(InfoDetailActivity.this, R.mipmap.info_gooded_icon);
                Drawable normal = ContextCompat.getDrawable(InfoDetailActivity.this, R.mipmap.info_good_icon);
                tvDetailGood.setCompoundDrawablesWithIntrinsicBounds(null, entity.getData().getStatus() == 1 ? select : normal, null, null);
                tvDetailGood.setText(entity.getData().getStatus() == 1 ? detailEntity.getData().getPraise_nums() + 1 + "" : detailEntity.getData().getPraise_nums() - 1 + "");
                detailEntity.getData().setPraise_nums(entity.getData().getStatus() == 1 ? detailEntity.getData().getPraise_nums() + 1 : detailEntity.getData().getPraise_nums() - 1);
                EventBus.getDefault().post(new MessageEvent(EVENT_INFO_CODE));
            }

            @Override
            public void onFailure(ApiException e) {

            }
        });
    }

    /**
     * 联系
     */
    private void contractInfo() {

        NormalDialog dialog = showAlterDialog("拨打电话", detailEntity.getData().getMobile());
        dialog.btnText("取消", "呼叫");
        dialog.setOnBtnClickL(null, new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                //用intent启动拨打电话。
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + detailEntity.getData().getMobile()));
                if (ActivityCompat.checkSelfPermission(InfoDetailActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    showToast("请确认拨打电话的权限");
                    return;
                }
                startActivity(intent);
            }
        });

    }
}
